package com.action.ui.activity.user;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.action.childbase.ChildBaseActivity;
import com.action.entity.UserAliSncode;
import com.action.entity.params.WithDepositParam;
import com.action.service.pressenter.MemberPressenter;
import com.action.ui.view.DecimalEditText;
import com.action.utils.LocUtils;
import com.action.utils.SingleClick;
import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.base.app_core.base.ActionPacketView;
import com.base.app_core.model.Paginated;
import com.base.app_core.service.pressenter.XYBUPressenter;
import com.base.app_core.service.user.model.User;
import com.base.app_core.service.user.model.UserAccount;
import com.base.app_core.util.AppConstants;
import com.base.app_core.util.MaterialDialogHelper;
import com.base.app_core.util.Preferences;
import com.base.app_core.util.XYBAUtils;
import com.blankj.utilcode.util.StringUtils;
import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.thread.EventThread;
import com.xinglai.yun.R;

import java.math.BigDecimal;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

import static com.base.app_core.service.pressenter.XYBUPressenter.WITHTYPE_ALI;
import static com.base.app_core.service.pressenter.XYBUPressenter.WITHTYPE_WEIXIN;

public class WithdrawDepositActivity extends ChildBaseActivity<XYBUPressenter>
        implements ActionPacketView.DepositView
        , ActionPacketView.payView {
    @BindView(R.id.cantixianjine)
    TextView mcantixianjine;
    @BindView(R.id.stockCountTag)
    TextView mStockCountTag;
    @BindView(R.id.top_right_edit)
    TextView mHistoryLogLabel;
    @BindView(R.id.tag_deposit)
    TextView tagDeposit;
    @BindView(R.id.close_category_list)
    ImageView mclose_category_list;
    @BindView(R.id.depositMoney)
    DecimalEditText depositMoney;


    @Inject
    WithDepositParam withDepositParam;
    @BindView(R.id.btndeposit)
    Button mBtnDeposit;
    @Inject
    LocUtils locUtils;
    @Inject
    User user;
    @Inject
    UserAccount userAccount;
    @Inject
    MemberPressenter memberPressenter;

    private String moneyPost;
    private String stockPrice;
    private String stockPost;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_withdraw_deposit;
    }

    /**
     * 0表示支付宝提现，1表示微信提现
     */
    int type = WITHTYPE_ALI;



    @Override
    protected void setupComponent() {
        super.setupComponent();
        getChildViewComponent().inject(this);
    }

    private String getMoneyByStockCount(String stockcount) {
        String price = stockPrice;
        if (StringUtils.isEmpty(stockcount) || StringUtils.isEmpty(price)) {
            return "";
        }
        BigDecimal bigDecimal = new BigDecimal(stockcount);
        BigDecimal stockPrice = new BigDecimal(price);
        return bigDecimal.multiply(stockPrice).setScale(AppConstants.ACOUNT_DEFAULT_NUM, BigDecimal.ROUND_DOWN).toPlainString();
    }

    private String getStockCountByMoney(String money) {
        if (userAccount == null || StringUtils.isEmpty(stockPrice)) {
            return "";
        }
        if (StringUtils.isEmpty(money))
            return "";
        BigDecimal bigDecimal = new BigDecimal(money);
        BigDecimal stockPrice = new BigDecimal(this.stockPrice);
        return bigDecimal.divide(stockPrice, AppConstants.STOCK_COUNT_DEFAULT_NUM, BigDecimal.ROUND_DOWN).toPlainString();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus.get().unregister(this);
    }

    @Subscribe(thread = EventThread.MAIN_THREAD)
    public void consumeWithDepositParam(final WithDepositParam withDepositParam) {
        MaterialDialogHelper.showSingleText(WithdrawDepositActivity.this, "是否马上提现", "取消", "提现", new MaterialDialogHelper.onItemClickLisener() {
            @Override
            public void onPosiClick(MaterialDialog dialog, DialogAction which) {
                if (SingleClick.isSingle()) {
                    showProgress();
                    mPresenter.postDeposit(withDepositParam.getType(), withDepositParam.getStockCount(), withDepositParam.getAliAccount());
                }
                dialog.dismiss();
            }

            @Override
            public void onNatiClick(MaterialDialog dialog, DialogAction which) {
                dialog.dismiss();
            }
        });
    }

    @Override
    protected void initView() {
        super.initView();
        setToolBar("提现");
        try {
            stockPrice = userAccount.getStockPrice();
            mHistoryLogLabel.setVisibility(View.GONE);
            withDepositParam.setRealName(user.getRealName());
            withDepositParam.setAliAccount(user.getAliAccount());
            withDepositParam.setType(WITHTYPE_WEIXIN);//默认支付宝
            RxBus.get().register(this);
            String account = userAccount.getAccount();
            if (!StringUtils.isEmpty(account)) {
                mcantixianjine.setText("提现金额("+new BigDecimal(account).setScale(AppConstants.ACOUNT_DEFAULT_NUM, BigDecimal.ROUND_DOWN).toPlainString() + "元)");
            } else {
                //TODO 通过接口返回用户账户数据
                showToast("获取用户账户数据失败,请重试");
            }
        } catch (Exception e) {
            e.printStackTrace();
            showToast("获取用户账户数据失败,请重试");
            finish();
        }


        depositMoney.setTextWatcher(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                try {
                    mStockCountTag.setText("="+getStockCountByMoney(depositMoney.getText().toString())+"股");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        String withDrar = Preferences.getDefault().getString(AppConstants.SP.WITH_DRAW_TYPE_LIMIT, null);
        if (withDrar == null || "0".equals(withDrar)) {
            mBtnDeposit.setVisibility(View.GONE);
        } else if ("1".equals(withDrar)) {
        } else if ("2".equals(withDrar)) {
        } else if ("3".equals(withDrar)) {
            type = WITHTYPE_ALI;
        } else if ("4".equals(withDrar)) {
            type = WITHTYPE_WEIXIN;
        }

        memberPressenter.attachView(this);
    }


    @OnClick({R.id.btndeposit, R.id.deposit_log})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btndeposit:
                //提现
                if(StringUtils.isEmpty(depositMoney.getText().toString())){
                   showToast("金额不能为空");
                   return;
                }
                stockPost=getStockCountByMoney(depositMoney.getText().toString());
                if (new BigDecimal(userAccount.getStockCount()).setScale(2, BigDecimal.ROUND_DOWN)
                        .compareTo(new BigDecimal(stockPost).setScale(2, BigDecimal.ROUND_DOWN)) < 0) {
                    showToast("账户金额不足");
                    return;
                }

                moneyPost = getMoneyByStockCount(stockPost);
                if (new BigDecimal(moneyPost).setScale(1, BigDecimal.ROUND_HALF_DOWN).compareTo(new BigDecimal(1).setScale(1, BigDecimal.ROUND_HALF_DOWN)) < 0) {
                    showToast("提现金额不得低于1元");
                    return;
                }
                withDepositParam.setStockCount(stockPost);
                withDepositParam.setDepositMoney(moneyPost);
                MaterialDialogHelper.showSingleText(WithdrawDepositActivity.this, "是否确定提现" + stockPost + "股数到微信",
                        "取消", "提现", new MaterialDialogHelper.onItemClickLisener() {
                            @Override
                            public void onPosiClick(MaterialDialog dialog, DialogAction which) {
                                depositByWeiXin();
                            }

                            @Override
                            public void onNatiClick(MaterialDialog dialog, DialogAction which) {
                                if (dialog != null) {
                                    dialog.dismiss();
                                }
                            }
                        });

                break;
            case R.id.deposit_log:
                if (SingleClick.isSingle()) {
                    startActivity(new Intent(this, HistoryDepositActivy.class));
                }
                break;
        }
    }

    private void depositByWeiXin() {
        if (SingleClick.isSingle()) {
            showProgress();
            mPresenter.postDeposit(withDepositParam.getType(), withDepositParam.getStockCount(), user.getAliSnCode());
        }
    }

    private void deposit() {
        if (SingleClick.isSingle()) {
            showProgress();
            mPresenter.postDeposit(withDepositParam.getType(), withDepositParam.getStockCount(), user.getAliSnCode());
        }
    }

    @Override
    public void notifyError(String errorCode, String content) {
        super.notifyError(errorCode, content);
        if ("1046".equals(errorCode)) {
            XYBAUtils.gotoURL(AppConstants.ROUTEURI.BINDALIACCOUNT);
        }
    }

    @Override
    public void doDepositSuccess(String data) {
        dismissProgress();
        if (SingleClick.isSingle()) {
            BigDecimal decimal = new BigDecimal(userAccount.getAccount()).subtract(new BigDecimal(moneyPost));
            userAccount.setAccount(decimal.toPlainString());
            BigDecimal subtract = new BigDecimal(userAccount.getStockCount()).subtract(new BigDecimal(stockPost));
            userAccount.setStockCount(subtract.toPlainString());
            RxBus.get().post(user);
            if (type == WITHTYPE_ALI) {
                startActivity(new Intent(this, DepositSuccessActivity.class)
                        .putExtra(AppConstants.EXTRA.TYPE_EXTRA, "支付宝"));
            } else if (type == WITHTYPE_WEIXIN) {
                startActivity(new Intent(this, DepositSuccessActivity.class)
                        .putExtra(AppConstants.EXTRA.TYPE_EXTRA, "微信"));
            }
            finish();
        }
    }

    @Override
    public <T> void notifyData(T object, Class tClass, Paginated paginated) {
        super.notifyData(object, tClass, paginated);
        if (object instanceof UserAliSncode) {
            UserAliSncode aliSncode = (UserAliSncode) object;
            if (!StringUtils.isEmpty(aliSncode.getAliAccount())) {
                Preferences.putString(AppConstants.SP.ALI_ACCOUNT, aliSncode.getAliAccount());
                user.setAliAccount(aliSncode.getAliAccount());
            }

            if (!StringUtils.isEmpty(aliSncode.getUserRealName())) {
                Preferences.putString(AppConstants.SP.USER_REALNAME, aliSncode.getUserRealName());
                user.setRealName(aliSncode.getUserRealName());
            }

            new MaterialDialog.Builder(WithdrawDepositActivity.this)
                    .title("提示")
                    .content("提现金额:" + depositMoney.getText().toString() + "元" +
                            "\n支付宝账号:" + user.getAliAccount() +
                            "\n真实名称:" + user.getRealName())
                    .positiveText("确认提现")
                    .negativeText("取消")
                    .neutralText("换绑")
                    .onAny(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            if (which == DialogAction.NEUTRAL) {
                                XYBAUtils.gotoURL(AppConstants.ROUTEURI.BINDALIACCOUNT);
                                dialog.dismiss();
                            } else if (which == DialogAction.POSITIVE) {
                                deposit();
                                dialog.dismiss();
                            } else if (which == DialogAction.NEGATIVE) {
                                dialog.dismiss();
                            }
                        }
                    }).show();

        }
    }

    @Override
    public void AliPayRequest(String data) {

    }
}
